package cjj;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/admin/publishBook")
@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2,
        maxFileSize = 1024 * 1024 * 10,
        maxRequestSize = 1024 * 1024 * 50)
public class AdminPublishBookServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置字符编码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        // 验证管理员身份
        Integer adminId = (Integer) request.getSession().getAttribute("adminId");
        if (adminId == null) {
            response.sendRedirect("/admin/login");
            return;
        }

        // 获取表单参数
        String title = request.getParameter("title");
        String author = request.getParameter("author");
        String publisher = request.getParameter("publisher");
        int publishYear = Integer.parseInt(request.getParameter("publishYear"));
        int pages = Integer.parseInt(request.getParameter("pages"));
        String language = request.getParameter("language");
        String translator = request.getParameter("translator");
        String description = request.getParameter("description");
        Part coverImagePart = request.getPart("coverImage");

        // 数据验证
        if (title == null || title.isEmpty() || author == null || author.isEmpty() ||
                publisher == null || publisher.isEmpty() || description == null || description.isEmpty()) {
            request.getSession().setAttribute("errorMessage", "书名、作者、出版社和简介不能为空");
            response.sendRedirect(request.getContextPath() + "/cjj/publish_book.jsp");
            return;
        }

        // 处理封面图片上传
        String coverImagePath = null;
        if (coverImagePart != null && coverImagePart.getSize() > 0) {
            try {
                String fileName = extractFileName(coverImagePart);
                String uniqueFileName = generateUniqueFileName(fileName);

                String uploadPath = getServletContext().getRealPath("/") + "uploads" + File.separator + "books";
                File uploadDir = new File(uploadPath);
                if (!uploadDir.exists()) {
                    uploadDir.mkdirs();
                }

                String savePath = uploadPath + File.separator + uniqueFileName;
                coverImagePart.write(savePath);
                coverImagePath = "uploads/books/" + uniqueFileName;
            } catch (Exception e) {
                request.getSession().setAttribute("errorMessage", "上传图片失败: " + e.getMessage());
                response.sendRedirect(request.getContextPath() + "/cjj/publish_book.jsp");
                return;
            }
        } else {
            request.getSession().setAttribute("errorMessage", "封面图片不能为空");
            response.sendRedirect(request.getContextPath() + "/cjj/publish_book.jsp");
            return;
        }

        // 数据库操作
        try (Connection conn = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/webproject_2025?useUnicode=true&characterEncoding=UTF-8",
                "root", "root")) {

            String sql = "INSERT INTO book (TITLE, AUTHOR, PUBLISHER, PUBLISH_YEAR, PAGES, LANGUAGE, TRANSLATOR, DESCRIPTION, COVER_IMAGE) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";

            try (PreparedStatement stmt = conn.prepareStatement(sql)) {
                stmt.setString(1, title);
                stmt.setString(2, author);
                stmt.setString(3, publisher);
                stmt.setInt(4, publishYear);
                stmt.setInt(5, pages);
                stmt.setString(6, language);
                stmt.setString(7, translator);
                stmt.setString(8, description);
                stmt.setString(9, coverImagePath);

                int rows = stmt.executeUpdate();
                if (rows > 0) {
                    request.getSession().setAttribute("successMessage", "图书发布成功");
                } else {
                    request.getSession().setAttribute("errorMessage", "图书发布失败，请重试");
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            request.getSession().setAttribute("errorMessage", "数据库错误: " + e.getMessage());
        } finally {
            response.sendRedirect(request.getContextPath() + "/cjj/publish_book.jsp");
        }
    }

    private String extractFileName(Part part) {
        String contentDisp = part.getHeader("content-disposition");
        String[] items = contentDisp.split(";");
        for (String item : items) {
            if (item.trim().startsWith("filename")) {
                return item.substring(item.indexOf("=") + 2, item.length() - 1);
            }
        }
        return "";
    }

    private String generateUniqueFileName(String originalFileName) {
        String timestamp = dateFormat.format(new Date());
        String extension = "";
        int dotIndex = originalFileName.lastIndexOf('.');
        if (dotIndex > 0) {
            extension = originalFileName.substring(dotIndex);
        }
        return timestamp + "_" + System.currentTimeMillis() + extension;
    }
}